% fig5 吸引盆(AttractionBasin)

clear; clc; close all;

%% —— 公共参数 —— 
g11 = 1; g12 = 1; g21 = -2; g22 = 2;
mu  = 0.58;                       % Fig.5(a) 的 μ
init_seeds = [                   % 四个参考初值
    0.1,  0.1;
   -0.1, -0.1;
    0.1, -0.1;
   -0.1,  0.1
];
seed_colors = [                  % 四个吸引域的颜色（同 Fig.4(c)）
    1.00, 0.00, 1.00;   % 品红 (0.1,0.1)
    0.60, 0.30, 0.00;   % 棕色 (-0.1,-0.1)
    0.50, 1.00, 0.50;   % 草绿 (0.1,-0.1)
    0.00, 1.00, 1.00;   % 青色 (-0.1,0.1)
];

%% —— 轨迹参数 —— 
Niter  = 1000;   % 迭代总步数
Ntrans = 200;   % 舍弃热身步数

%% —— 1. 预计算四个参考吸引子代表点 —— 
rep_pts = zeros(4,2);
for s = 1:4
    x = init_seeds(s,1);
    y = init_seeds(s,2);
    for k = 1:Niter
        x_next = mu*x + g11*sin(x) + g12*sin(y);
        y_next = mu*y + g21*sin(x) + g22*sin(y);
        x = x_next;  y = y_next;
        if k > Ntrans
            traj(k-Ntrans, :) = [x,y];
        end
    end
    % 取后半段轨迹的均值作为代表点
    rep_pts(s,:) = mean(traj,1);
end
clear traj

%% —— 2. 构建初值网格 —— 
res = 400;   % 网格分辨率 (800×800)
x0_vec = linspace(-6,6,res);
y0_vec = linspace(-6,6,res);

basin_idx = zeros(res,res);  % 存放每个初值属于哪条种子

%% —— 3. 并行遍历网格，分类属域 —— 
parfor ix = 1:res
    xx = x0_vec(ix);
    local_idx = zeros(1,res);
    for iy = 1:res
        x = xx;  y = y0_vec(iy);
        % 迭代
        for k = 1:Niter
            x_next = mu*x + g11*sin(x) + g12*sin(y);
            y_next = mu*y + g21*sin(x) + g22*sin(y);
            x = x_next;  y = y_next;
        end
        % 取最终点 (x,y)
        final_pt = [x,y];
        % 计算到四个 rep_pts 的欧氏距离，找最小
        d2 = sum((rep_pts - final_pt).^2, 2);
        [~, smin] = min(d2);
        local_idx(iy) = smin;
    end
    basin_idx(ix,:) = local_idx;
end

%% —— 4. 可视化吸引盆 —— 
figure;
hold on;
for s = 1:4
    mask = (basin_idx' == s);  % 注意转置后行对应 y0，列对应 x0
    % 用逻辑索引画点
    [Y,X] = find(mask);
    scatter(x0_vec(X), y0_vec(Y), 5, ...
        repmat(seed_colors(s,:), numel(X),1), 'filled');
end
xlabel('x_0','FontSize',14);
ylabel('y_0','FontSize',14);
title('Fig.5(a) 吸引盆(μ=0.58)','FontSize',16);
xlim([-6,6]);
ylim([-6,6]);
axis equal tight;

